package com.adam.example;

import com.carrotsearch.hppc.ObjectLookupContainer;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesResponse;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.admin.indices.close.CloseIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse;
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsResponse;
import org.elasticsearch.client.IndicesAdminClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

public class IndicesAdminExample {

    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        TransportClient transportClient = TransportClientHolder.getInstance().getTransportClient();
        IndicesAdminClient indicesAdminClient = transportClient.admin().indices();

        IndicesExistsResponse indicesExistsResponse = indicesAdminClient.prepareExists("test_books").get();
        System.out.println("索引是否存在：" + indicesExistsResponse.isExists());

        TypesExistsResponse typesExistsResponse = indicesAdminClient.prepareTypesExists("test_books")
                .setTypes("IT").get();
        System.out.println("类型是否存在：" + typesExistsResponse.isExists());

//        CreateIndexResponse createIndexResponse = indicesAdminClient.prepareCreate("test")
//                .setSettings(Settings.builder()
//                        .put("index.number_of_shards", 1)
//                        .put("index.number_of_replicas", 0)
//                        .build()
//                ).get();
//        System.out.println("创建索引：" + createIndexResponse.isAcknowledged());

        UpdateSettingsResponse updateSettingsResponse = indicesAdminClient.prepareUpdateSettings("test")
                .setSettings(Settings.builder()
                        .put("index.number_of_replicas", 0)
                        .build()
                ).get();
        System.out.println("更新索引settings:" + updateSettingsResponse.isAcknowledged());

        GetSettingsResponse getSettingsResponse = indicesAdminClient.prepareGetSettings("test", "test_books")
                .get();
        for(ObjectObjectCursor<String, Settings> cursor: getSettingsResponse.getIndexToSettings()) {
            String index = cursor.key;
            Settings settings = cursor.value;
            int numberOfShards = settings.getAsInt("index.number_of_shards", null),
                    numberOfReplicas = settings.getAsInt("index.number_of_replicas", null);
            System.out.println("获取索引" + index + " settings: numberOfShards=" + numberOfShards + ",numberOfReplicas=" + numberOfReplicas);
        }

//        PutMappingResponse putMappingResponse = indicesAdminClient.preparePutMapping("test_books").setType("IT")
//                .setSource("{" +
//                        "\"properties\": {" +
//                        "\"name\": {\"type\": \"keyword\"}" +
//                        "}" +
//                        "}", XContentType.JSON).get();
//        System.out.println(putMappingResponse.isAcknowledged());

        GetMappingsResponse getMappingsResponse = indicesAdminClient.prepareGetMappings("test_books").get();
        ImmutableOpenMap<String, MappingMetaData> mappings = getMappingsResponse.getMappings().get("test_books");
        MappingMetaData metaData = mappings.get("IT");
        System.out.println("获取mappings: " + metaData.getSourceAsMap());

//        DeleteIndexResponse deleteIndexResponse = indicesAdminClient.prepareDelete("test").get();
//        System.out.println(deleteIndexResponse.isAcknowledged());

        RefreshResponse refreshResponse = indicesAdminClient.prepareRefresh("test").get();
        System.out.println("刷新索引：totalShards=" + refreshResponse.getTotalShards() + ",successful=" + refreshResponse.getSuccessfulShards());

        CloseIndexResponse closeIndexResponse = indicesAdminClient.prepareClose("test").get();
        System.out.println("关闭索引：" + closeIndexResponse.isAcknowledged());

        OpenIndexResponse openIndexResponse = indicesAdminClient.prepareOpen("test").get();
        System.out.println("打开索引：" + openIndexResponse.isAcknowledged());

        IndicesAliasesResponse indicesAliasesResponse = indicesAdminClient.prepareAliases()
                .addAlias("test", "test_1")
                .get();
        System.out.println("添加索引别名：" + indicesAliasesResponse.isAcknowledged());

        GetAliasesResponse getAliasesResponse1 = indicesAdminClient.prepareGetAliases("test_1").get();
        ObjectLookupContainer<String> objectLookupContainer = getAliasesResponse1.getAliases().keys();
        List<String> indexNameList = new LinkedList<>();
        for(ObjectCursor<String> objectCursor: objectLookupContainer) {
            indexNameList.add(objectCursor.value);
        }
        System.out.println("获取别名对应的索引：" + indexNameList);

        GetAliasesResponse getAliasesResponse2 = indicesAdminClient.getAliases(new GetAliasesRequest().indices("test")).get();
        List<AliasMetaData> aliasMetaDataList = getAliasesResponse2.getAliases().get("test");
        List<String> aliasNameList = aliasMetaDataList.stream().map(AliasMetaData::getAlias).collect(Collectors.toList());
        System.out.println("获取索引名对应的别名：" + aliasNameList);

        transportClient.close();
    }

}
